<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ImeiAll, CardIdAll, uploadRealTimeFile, uploadCameraFile } from '@/utils/api.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import wlsPopup from '@/components/common/wls-popup.vue'
import delimg from '@/assets/images/del.png'
const emit = defineEmits(['refreshcar'])
let type = '实时相机';
let areaId = "";
let imeiList = [];
let upl = [];
const isup = ref(false);
const ruleForm = ref({
    name: ''
})
const rules = reactive({
    name: [
        {
            required: true,
            message: '请请选择相机',
            trigger: 'change',
        },
    ]
})

const ivlist = ref([])
const ruleFormRef = ref(null)

const getImeiAll = async () => {
    if (type == '实时相机') {
        let res = await ImeiAll(areaId)
        if (res.code == '200') {
            imeiList = res.data;
        }
    } else {
        let res = await CardIdAll(areaId)
        if (res.code == '200') {
            imeiList = res.data;
        }
    }

}

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {

            const loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            let count = 0;
            const totalIterations = upl.length;
            try {
                for (let i = 0; i < totalIterations; i++) {
                    const e = upl[i];
                    let formData = new FormData();
                    formData.append('areaId', e.areaId);
                    formData.append('cameraEnvirId', e.cameraEnvirId);
                    formData.append('file', e.file);

                    if (type == '实时相机') {
                        uploadRealTimeFile(formData)
                            .then(res => {
                                count++;
                                if (count === totalIterations) {
                                    loading.close();
                                    ElMessage({
                                        type: 'success',
                                        message: '上传成功'
                                    });
                                    emit('refreshcar', '')
                                    isup.value = false;


                                }
                            })
                            .catch(err => {
                                ElMessage({
                                    type: 'warning',
                                    message: '文件过大请求超时,上传失败'
                                })
                                loading.close();
                                isup.value = false;

                                emit('refreshcar', '')
                            })
                    } else {
                        // uploadCameraFile
                        uploadCameraFile(formData)
                            .then(res => {
                                count++;
                                if (count === totalIterations) {
                                    loading.close();
                                    ElMessage({
                                        type: 'success',
                                        message: '上传成功'
                                    });
                                    emit('refreshcar', '')
                                    isup.value = false;


                                }
                            })
                            .catch(err => {
                                ElMessage({
                                    type: 'warning',
                                    message: '文件过大请求超时,上传失败'
                                })
                                loading.close();
                                isup.value = false;

                                emit('refreshcar', '')
                            })
                    }


                }
                // 执行后续代码
                // 在这里写下你想要执行的代码
            } catch (error) {
                // 请求失败，中止循环
                loading.close();
                isup.value = false;
                ivlist.value = [];
                upl.value = [];
                console.error(error);
                emit('refreshcar', '')
                // 在这里写下你想要执行的代码
            }


        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
    isup.value = false
}

const open = (data) => {
    type = data;
    console.log(type);
    getImeiAll();
    ivlist.value = [];
    upl.value = [];
    ruleForm.value.name = '';
    isup.value = true
}

const cameraup = (event) => {
    let file = event.target.files;
    for (let i = 0; i < file.length; i++) {
        console.log(file[i]);
        let imgUrl = URL.createObjectURL(file[i]);
        let z = {
            id: file[i].lastModified,
            file: file[i],
            url: imgUrl,
            type: file[i].type
        }
        ivlist.value.push(z)
        upl.push(
            {
                areaId: areaId,
                cameraEnvirId: ruleForm.value.name,
                file: file[i]
            }
        )

    }
    event.target.value = '';
}

const isim = (data) => {
    if (data) {
        let str = data.split('/')[0]
        if (str === 'video') {
            return 1
        } else {
            return 2
        }
    }
}

const delu = (x) => {
    ivlist.value.splice(x, 1);
}

onMounted(() => {
    areaId = window.sessionStorage.getItem('areaId');

})

defineExpose({ open })

</script>
<template>
    <wls-popup v-if="isup">
        <div class="wls-u">
            <div class="d-lkb-c" @click.stop="resetForm(ruleFormRef)">
                <!-- <svg class="wls-icon" aria-hidden="true" style="width: .4rem;height: 0.4rem;">
                    <use xlink:href="#icon-guanbi"></use>
                </svg> -->
                <i class="icon iconfont icon-guanbi" style="font-size: .2rem;"></i>
            </div>
            <div class="wls-info-title">
                <div></div>
                <div><span>上传</span></div>
            </div>
            <div style="height: 0.16rem;"></div>
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="top" class="demo-ruleForm"
                size="large">
                <el-row>
                    <el-col :span="16">
                        <el-form-item label="选择相机" prop="name">
                            <el-select v-model="ruleForm.name" style="width: 100%;" clearable placeholder="请先选择要上传的相机">
                                <el-option v-for="(i, index) in imeiList" :key="i.id" :label="i.imei" :value="i.id" />
                            </el-select>
                        </el-form-item></el-col>
                </el-row>
            </el-form>

            <div class="wls-u-btn">
                <!-- <svg class="wls-icon" aria-hidden="true">
                    <use xlink:href="#icon-tianjia1"></use>
                </svg> -->
                <i style="color: var(--wls-color);" class="icon iconfont icon-tianjia1"></i>
                <span style="margin-left: 0.08rem;">选择文件</span>
                <input class="wls-upload" @change="cameraup($event, 0)" ref="upload" multiple
                    accept="image/jpeg, image/png, video/mp4, video/quicktime" type="file" />
            </div>

            <div class="wls-u-siv scol">
                <ul class="wls-u-ul">
                    <li v-for="(i, index) in ivlist" :key="i.id">
                        <div class="d-lkb-c" @click.stop="delu(index)" style="top: 0.04rem;right: 0.04rem;">
                            <img :src="delimg" alt="">
                        </div>
                        <video v-if="isim(i.type) === 1" :src="i.url"></video>
                        <img v-else :src="i.url" alt="">
                    </li>
                </ul>
            </div>

            <div style="margin: 0.16rem 0;display: flex;align-items: center;justify-content: center;">
                <el-button type="primary" @click.stop="submitForm(ruleFormRef)">保存</el-button>
                <el-button @click.stop="resetForm(ruleFormRef)">取消</el-button>
            </div>
        </div>
    </wls-popup>
</template>
<style scoped>
.wls-u {
    width: 7rem;
    padding: .24rem;
    background-color: #fff;
    position: relative;
    overflow: hidden;
}

.wls-u-btn {
    width: 100%;
    margin-bottom: 0.16rem;
    display: flex;
    align-items: center;
    color: var(--wls-color);
    position: relative;
}

.wls-u-siv {
    width: 100%;
    max-height: 5rem;
}

.wls-u-ul {
    width: 100%;
    overflow: hidden;
}

.wls-u-ul li {
    width: calc((100% - 0.48rem) / 4);
    height: 1.2rem;
    float: left;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #000;
    margin: 0 0.16rem 0.16rem 0;
    position: relative;
    overflow: hidden;
}

.wls-u-ul li img {
    width: 100%;
    height: 100%;
}

.wls-u-ul li video {
    max-width: 100%;
    max-height: 100%;
}

.wls-u-ul li:nth-child(4n) {
    margin-right: 0;
}
</style>